<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择所属仓库" clearable style="width: 240px">
          <el-option
            v-for="item in warehouseOptions"
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库区编码" prop="areaCode">
        <el-input
          v-model="queryParams.areaCode"
          placeholder="请输入库区编码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库区名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入库区名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库区类型" prop="areaType">
        <el-select v-model="queryParams.areaType" placeholder="请选择库区类型" clearable style="width: 240px">
          <el-option
            v-for="dict in areaTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库区状态" prop="areaStatus">
        <el-select v-model="queryParams.areaStatus" placeholder="请选择库区状态" clearable style="width: 240px">
          <el-option
            v-for="dict in areaStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wms:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:area:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:area:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wms:area:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <!-- 库区树 -->
      <el-col :span="8" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeSearchValue"
            placeholder="请输入库区名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="tree-container">
          <el-tree
            :data="areaTreeData"
            :props="{ label: 'areaName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="areaTreeRef"
            node-key="areaId"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      
      <!-- 库区列表 -->
      <el-col :span="16" :xs="24">
        <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="库区ID" align="center" prop="areaId" v-if="false" />
          <el-table-column label="库区编码" align="center" prop="areaCode" />
          <el-table-column label="库区名称" align="center" prop="areaName" />
          <el-table-column label="所属仓库" align="center" prop="warehouseName" />
          <el-table-column label="库区类型" align="center" prop="areaType">
            <template #default="scope">
              {{ areaTypeOptions.find(dict => dict.value === scope.row.areaType)?.label }}
            </template>
          </el-table-column>
          <el-table-column label="库区状态" align="center" prop="areaStatus">
            <template #default="scope">
              <dict-tag :options="areaStatusOptions" :value="scope.row.areaStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="排序号" align="center" prop="sortOrder" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['wms:area:edit']"
              >修改</el-button>
              <el-button
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['wms:area:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改库区信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="areaRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择所属仓库" style="width: 100%">
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="父库区" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="parentAreaOptions"
            :props="{ label: 'areaName', value: 'areaId', children: 'children' }"
            value-key="areaId"
            placeholder="请选择父库区"
            check-strictly
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库区编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入库区编码" />
        </el-form-item>
        <el-form-item label="库区名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入库区名称" />
        </el-form-item>
        <el-form-item label="库区类型" prop="areaType">
          <el-select v-model="form.areaType" placeholder="请选择库区类型">
            <el-option
              v-for="dict in areaTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="库区状态" prop="areaStatus">
          <el-radio-group v-model="form.areaStatus">
            <el-radio
              v-for="dict in areaStatusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { listArea, treeArea, getArea, delArea, addArea, updateArea, exportArea, listAreaByWarehouse } from "@/api/wms/base/area";
import { listWarehouse } from "@/api/wms/base/warehouse";
import { getCurrentInstance, ref, watch } from 'vue';

const { proxy } = getCurrentInstance();

// 库区状态选项
const areaStatusOptions = ref([
  { value: "0", label: "启用" },
  { value: "1", label: "禁用" }
]);

// 库区类型选项
const areaTypeOptions = ref([
  { value: "1", label: "原材料区" },
  { value: "2", label: "半成品区" },
  { value: "3", label: "成品区" },
  { value: "4", label: "不良品区" },
  { value: "5", label: "退货区" },
  { value: "6", label: "临时区" }
]);

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 库区表格数据
const areaList = ref([]);
// 库区树数据
const areaTreeData = ref([]);
// 树搜索值
const treeSearchValue = ref("");
// 当前选中的树节点
const currentNode = ref(null);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 仓库选项
const warehouseOptions = ref([]);
// 父库区选项
const parentAreaOptions = ref([]);
// 表单参数
const form = ref({
  areaId: null,
  parentId: null,
  warehouseId: null,
  areaCode: null,
  areaName: null,
  areaType: null,
  areaLevel: null,
  areaPath: null,
  isLeaf: true,
  sortOrder: 1,
  areaStatus: "0",  // 默认启用
  remark: null
});
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  warehouseId: null,
  areaCode: null,
  areaName: null,
  areaType: null,
  areaStatus: null,
  parentId: null
});

// 表单校验
const rules = ref({
  warehouseId: [
    { required: true, message: "所属仓库不能为空", trigger: "change" }
  ],
  areaCode: [
    { required: true, message: "库区编码不能为空", trigger: "blur" }
  ],
  areaName: [
    { required: true, message: "库区名称不能为空", trigger: "blur" }
  ],
  areaType: [
    { required: true, message: "库区类型不能为空", trigger: "change" }
  ],
  sortOrder: [
    { required: true, message: "排序号不能为空", trigger: "blur" }
  ],
  areaStatus: [
    { required: true, message: "库区状态不能为空", trigger: "change" }
  ]
});

/** 查询库区信息列表 */
function getList() {
  loading.value = true;
  listArea(queryParams.value).then(response => {
    areaList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询库区树结构 */
function getTreeList() {
  treeArea().then(response => {
    areaTreeData.value = response.data;
  });
}

/** 查询仓库下拉选项 */
function getWarehouseOptions() {
  listWarehouse().then(response => {
    warehouseOptions.value = response.rows;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    areaId: null,
    parentId: null,
    warehouseId: null,
    areaCode: null,
    areaName: null,
    areaType: null,
    areaLevel: null,
    areaPath: null,
    isLeaf: true,
    sortOrder: 1,
    areaStatus: "0",  // 默认启用
    remark: null
  };
  proxy.resetForm("areaRef");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.$refs["queryFormRef"].resetFields();
  if (proxy.$refs["areaTreeRef"]) {
    proxy.$refs["areaTreeRef"].setCurrentKey(undefined);
  }
  currentNode.value = null;
  queryParams.value.parentId = null;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.areaId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getWarehouseOptions();
  open.value = true;
  title.value = "添加库区信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getWarehouseOptions();
  const areaId = row.areaId || ids.value;
  getArea(areaId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改库区信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["areaRef"].validate(valid => {
    if (valid) {
      if (form.value.areaId != null) {
        updateArea(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getTreeList();
        });
      } else {
        addArea(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          getTreeList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const areaIds = row.areaId || ids.value;
  proxy.$modal.confirm('是否确认删除库区信息编号为"' + areaIds + '"的数据项?').then(function() {
    return delArea(areaIds);
  }).then(() => {
    getList();
    getTreeList();
    proxy.$modal.msgSuccess("删除成功");
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/wms/base/area/export', {
    ...queryParams.value
  }, `库区信息_${new Date().getTime()}.xlsx`);
}

/** 监听树搜索值变化 */
watch(treeSearchValue, (val) => {
  proxy.$refs["areaTreeRef"].filter(val);
});

/** 监听仓库选择变化 */
watch(() => form.value.warehouseId, (newVal) => {
  if (newVal) {
    listAreaByWarehouse(newVal).then(response => {
      parentAreaOptions.value = response.data;
      form.value.parentId = null;
    });
  } else {
    parentAreaOptions.value = [];
    form.value.parentId = null;
  }
});

/** 过滤节点 */
function filterNode(value, data) {
  if (!value) return true;
  return data.areaName.indexOf(value) !== -1;
}

/** 节点单击事件 */
function handleNodeClick(data) {
  currentNode.value = data;
  queryParams.value.parentId = data.areaId;
  handleQuery();
}

getList();
getTreeList();
getWarehouseOptions();
</script>

<style scoped>
.tree-container {
  margin-top: 10px;
  background: #fff;
  border: 1px solid #e5e6e7;
  border-radius: 4px;
  padding: 10px;
  height: calc(100vh - 230px);
  overflow: auto;
}

.head-container {
  margin-bottom: 10px;
}
</style>
